import { REG_EXP, SUCCESS_CODE } from '@/constants'
import { MinusCircleOutlined, PlusCircleOutlined, PlusOutlined } from '@ant-design/icons'
import { styled, Access } from '@umijs/max'
import { Input, Modal, TimePicker, Upload, UploadFile, message, Image } from 'antd'
import dayjs, { Dayjs } from 'dayjs'
import { useState } from 'react'

type Value = Record<string, {
  telephone: string
  qrCode: string
}>
interface ManagerInfoProps {
  value?: Value
  onChange?: (val: Value) => void
}

const Container = styled.div`
  width: max-content;
  border-radius: 8px;
  background: #f5f5f5;
  padding: 0 16px;
`
const Item = styled.div`
  width: 100%;
  display: flex;
  align-items: center;
  border-bottom: 1px solid #eeeeee;

  .label {
    width: 100px;
  }

  .value {
  }
`
const Add = styled.div`
  width: 100%;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
`
const format = 'HH:mm'

const ManagerInfo: React.FC<ManagerInfoProps> = (props) => {
  const [open, setOpen] = useState(false)
  const [startTime, setStartTime] = useState('')
  const [endTime, setEndTime] = useState<Dayjs>()
  const [telephone, setTelephone] = useState<string>('')
  const [qrCode, setQrCode] = useState<string>('')
  const [imgList, setImgList] = useState<string[]>([])
  const [previewCurrent, setPreviewCurrent] = useState(0)

  const keys = Object.keys(props.value || {})

  const getStartTime = (time: string) => {
    const _time = time.split(':')
    let _hour = parseInt(_time[0])
    let _minute = parseInt(_time[1]) + 1
    if (_minute === 60) {
      return `${String(_hour + 1).padStart(2, '0')}:00`
    }
    return `${String(_hour).padStart(2, '0')}:${String(_minute).padStart(2, '0')}`
  }

  const remove = (key: string) => {
    delete props.value![key]
    props.onChange?.({...props.value})
  }

  const addRow = () => {
    if (keys.length && keys.at(-1)?.endsWith('23:59')) {
      message.info('已无可分配时间')
      return
    }
    setOpen(true)
    setTelephone('')
    setStartTime(keys.length ? getStartTime(keys.at(-1)!.split('-')[1]) : '00:00')
    setEndTime(dayjs('23:59', format))
  }

  const onCancel = () => {
    setOpen(false)
  }

  const onOk = () => {
    if (!qrCode) {
      message.error('请输入客服二维码')
    } else if (!REG_EXP.NUMBER.test(telephone)) {
      message.error('请输入手机号')
    } else {
      const _value = {...props.value}
      _value[`${startTime}-${endTime?.format(format)}`] = {
        telephone,
        qrCode
      }
      props.onChange?.(_value)
      onCancel()
    }
  }

  const setDisableTime = (val: Dayjs, _keys: string[]) => {
    if (_keys.length < 1) {
      return {}
    }
    const _lastKey = _keys.at(-1)!
    const _time = _lastKey.split('-')[1].split(':')
    let _hour = parseInt(_time[0])
    let _minute = parseInt(_time[1]) + 1
    if (_minute >= 60) {
      _hour += 1
      _minute = 0
    }
    const disabledHours: number[] = []
    const disabledMinutes: number[] = []
    for (let i=0; i<_hour; i++) {
      disabledHours.push(i)
    }
    for (let i=0; i<60; i++) {
      disabledMinutes.push(i)
    }
    return {
      disabledHours: () => disabledHours,
      disabledMinutes: (hour: number) => {
        if (hour < _hour) return disabledMinutes
        if (hour === _hour) {
          return disabledMinutes.filter(i => i < _minute)
        }
        return []
      }
    }
  }

  const onFileUpLoadChange = (file: UploadFile) => {
      const { status, response } = file
      if (status === 'done' && response) {
        const { code, data, text } = response
        if (code === SUCCESS_CODE) {
          setQrCode(data)
        } else {
          Modal.error({
            title: '错误',
            content: text === '上传文件过大' ? '文件体积超过 2M，请重新上传' : '图片上传失败，请重试',
          })
          setQrCode('')
        }
      } else if (status === 'error') {
        setQrCode('')
      }
    }
  
    const openPreview = () => {
      setPreviewCurrent(0)
      setImgList([qrCode])
    }

  return <Container>
    {
      keys.map((key) => {
        return <Item key={key}>
          <div className="label">{ key }</div>
          <div className='value'>
            <div>手机号：{props.value![key].telephone || (props.value![key] as any)}</div>
            <div>
              <span>客服二维码：</span>
              {
                props.value![key].qrCode ? <img src={props.value![key].qrCode} style={{width: 60, height: 60}} /> : '--'
              }
            </div>
          </div>
          <Access accessible={key === keys.at(-1)}>
            <MinusCircleOutlined style={{color: 'red', cursor: 'pointer'}} onClick={() => remove(key)} />
          </Access>
        </Item>
      })
    }
    <Add onClick={addRow}>
      <PlusCircleOutlined style={{color: 'green'}} />
      <div style={{marginLeft: 8}}>添加联系方式</div>
    </Add>
    <Modal
      title='联系方式'
      open={open}
      onCancel={onCancel}
      onOk={onOk}
    >
      <div>时间段</div>
      <div style={{display: 'flex', alignItems: 'center', gap: 16, marginTop: 8}}>
        <div style={{borderRadius: 8, background: '#f5f5f5', lineHeight: '32px', padding: '0 16px'}}>{ startTime }</div>
        <div>{` - `}</div>
        <TimePicker
          format={format}
          value={endTime}
          onChange={setEndTime}
          disabledTime={val => setDisableTime(val, keys)}
          allowClear={false}
        />
      </div>
      <div style={{marginTop: 8}}>手机号</div>
      <Input style={{marginTop: 8}} placeholder='请输入人手机号' value={telephone} onChange={({target}) => setTelephone(target.value)} />
      <div style={{margin: '8px 0'}}>客服二维码</div>
      <Upload 
        action="/app/user/fileUp" listType="picture-card"
        accept='image/*'
        data={{type: 1}} maxCount={1}
        headers={{Authorization: localStorage.Authorization}}
        onChange={({file}) => onFileUpLoadChange(file)}
        onPreview={openPreview}
        onRemove={() => setQrCode('')}
      >
        {
          !qrCode ? <button style={{ border: 0, background: 'none' }} type="button">
            <PlusOutlined />
            <div style={{ marginTop: 8 }}>选择</div>
          </button> : null
        }
      </Upload>
    </Modal>
    <Image.PreviewGroup
      items={imgList}
      preview={{
        visible: imgList.length > 0,
        current: previewCurrent,
        onChange: (val) => {
          setPreviewCurrent(val)
        },
        onVisibleChange: (val) => {
          if (!val) setImgList([])
        }
      }}
    >
    </Image.PreviewGroup>
  </Container>
}

export default ManagerInfo